#include "stdafx.h"
#include "registry.h"

START_NAMESPACE

	CRegistry::CRegistry()
	{
		m_hKey = NULL;
	}
	
	CRegistry::~CRegistry()
	{
		Close();
	}

	bool CRegistry::Open(HKEY key,LPCTSTR sub_key,bool bCreate)
	{
		long r;
		
		if( bCreate)
			r = RegCreateKey( key, sub_key, &m_hKey);
		else
			r = RegOpenKey( key, sub_key, &m_hKey);

		return r == ERROR_SUCCESS;
	}
	
	bool CRegistry::Close()
	{
		if( m_hKey)
		{
			RegCloseKey( m_hKey);
			m_hKey = NULL;
		}

		return true;
	}

	bool CRegistry::Write(LPCTSTR key,DWORD value)
	{
		if( m_hKey == NULL) 	return false;
		return RegSetValueEx( m_hKey, key, 0, REG_DWORD, (LPBYTE)&value, sizeof( value)) == ERROR_SUCCESS;
	}
	
	bool CRegistry::Write(LPCTSTR key,LPCTSTR str)
	{
		if( m_hKey == NULL) 	return false;
		return RegSetValueEx( m_hKey, key, 0,REG_SZ, (LPBYTE)str, strlen( str)) == ERROR_SUCCESS;
	}
	
	bool CRegistry::Write(LPCTSTR key,LPBYTE binary,int length)
	{
		if( m_hKey == NULL) 	return false;
		return RegSetValueEx( m_hKey, key, 0,REG_BINARY, (LPBYTE)binary, length) == ERROR_SUCCESS;
	}

	bool CRegistry::Read(LPCTSTR key,DWORD &value)
	{
		if( m_hKey == NULL) 	return false;
		DWORD data_length = sizeof( value);
		DWORD type = REG_DWORD;

		return RegQueryValueEx( m_hKey, key, 0, &type, (LPBYTE)&value, &data_length) == ERROR_SUCCESS;
	}
	
	bool CRegistry::Read(LPCTSTR key,std::string &str)
	{
		if( m_hKey == NULL) 	return false;
		DWORD data_length = 255;
		DWORD type = REG_SZ;
		char buff[ 255];

		if( RegQueryValueEx( m_hKey, key, 0, &type, (LPBYTE)buff, &data_length) != ERROR_SUCCESS)
			return false;

		str = buff;
		return true;
	}
	
	bool CRegistry::Read(LPCTSTR key,LPBYTE binary,int length)
	{
		if( m_hKey == NULL) 	return false;
		DWORD data_length = length;
		DWORD type = REG_BINARY;
		return RegQueryValueEx( m_hKey, key, 0, &type, (LPBYTE)binary, &data_length) == ERROR_SUCCESS;
	}

	bool CRegistry::Read(LPCTSTR key,char* pBuffer)
	{
		if( m_hKey == NULL) 	return false;
		DWORD data_length = 255;
		DWORD type = REG_SZ;
		char buff[ 255];

		if( RegQueryValueEx( m_hKey, key, 0, &type, (LPBYTE)buff, &data_length) != ERROR_SUCCESS)
			return false;

		if (SF_strcpy( pBuffer, 255, buff) != S_OK)
		{
			_ASSERT(FALSE);
			return false;
		}
		return true;
	}


END_NAMESPACE